package com.huabo.monitor.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hbfk.entity.DealUserToken;
import com.hbfk.entity.TblStaffUtil;
import com.hbfk.util.FtpUtil;
import com.hbfk.util.ImportOrExportExcelUtil;
import com.hbfk.util.JsonBean;
import com.huabo.monitor.entity.*;
import com.huabo.monitor.service.*;
import com.huabo.monitor.util.ConstClass;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author meng
 * @date 2022-08-26 9:36
 * @description
 */
@RestController
@Slf4j
@Api(value = "评价管理-评价评分", tags = {"评价管理-评价评分所有接口"})
@RequestMapping(value = "/nbkz")
public class PjpfController {

    @Autowired
    PjpfService pjpfService;
    @Autowired
    TblAssessService assessService;

    @Autowired
    TblAssessService tblAssessService;

    @Autowired
    ITblStaffService iTblStaffService;
    @Autowired
    ITblAssessMarkService iTblAssessMarkService;

    @Autowired
    ITblTaskService iTblTaskService;
    @Autowired
    ITblAssesstempleService iTblAssesstempleService;

    @Autowired
    ITblAsseleCategoryService iTblAsseleCategoryService;

    @Autowired
    PjjgService pjjgService;

    @Autowired
    ITblAssesslevelService iTblAssesslevelService;

    @Autowired
    ITblAssessTargetService iTblAssessTargetService;

    @Autowired
    ITblAmorgProblemService iTblAmorgProblemService;
    @Autowired
    ITblAttachmentService iTblAttachmentService;
    @Autowired
    ITblAssesselementService iTblAssesselementService;
    @Autowired
    ITblFlowService iTblFlowService;
    @Autowired
    ITblAssessStaffService  iTblAssessStaffService;



    @GetMapping(value = "/pjgl/t08_proj_pingfen")
    @ApiOperation("评价评分-主页查询-发起")
    public JsonBean t08_proj_pingfen(
            @ApiParam(name = "pageNumber", value = "pageNumber") @RequestParam(value = "pageNumber", required = false) Integer pageNumber,
            @ApiParam(name = "selectedPlans", value = "评估项目的id", defaultValue = "734362") @RequestHeader("selectedPlans") BigDecimal selectedPlans,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {

        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        if (Objects.isNull(selectedPlans) || selectedPlans.equals("")) {
            return new JsonBean(400, "缺少评估人员", null);
        }

        //等价于 ==》 TblStaff user = (TblStaff) request.getSession().getAttribute("longUser");
        TblStaffUtil user = DealUserToken.parseUserToken(token);
        IPage iPage = new Page(pageNumber, ConstClass.DEFAULT_SIZE);
        iPage = pjpfService.getTblAssessGroupOrg(
                iPage,
                selectedPlans,
                user.getStaffid());
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("ASSID", selectedPlans);
        TblAssess tblAssess = pjpfService.getOne(wrapper);

        Map<String, Object> mv = new HashMap<>();
        mv.put("pageBean", iPage);
        mv.put("project", tblAssess);
        return new JsonBean(200, "success", mv);
    }

    @GetMapping(value = "/pjgl/proj_task_gradelist")
    @ApiOperation("评价评分-主页查询")
    public JsonBean proj_initiatePjgl(
            @ApiParam(name = "pageNumber", value = "pageNumber") @RequestParam(value = "pageNumber", required = false) Integer pageNumber,
            @ApiParam(name = "projkey", value = "评价项目编号") @RequestParam(value = "projkey", required = false) String projkey,
            @ApiParam(name = "projname", value = "评价项目名称") @RequestParam(value = "projname", required = false) String projname,
            @ApiParam(name = "startDate", value = "开始时间:格式年-月-日") @RequestParam(value = "startDate", required = false) String startDate,
            @ApiParam(name = "endDate", value = "结束日期") @RequestParam(value = "endDate", required = false) String endDate,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {

        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        //TblStaff user = (TblStaff) request.getSession().getAttribute("longUser");
        TblStaffUtil staff = DealUserToken.parseUserToken(token);

        IPage<TblAssessVo> iPage = new Page<>(pageNumber, ConstClass.DEFAULT_SIZE);

        iPage = pjpfService.findPageBean(
                iPage,
                staff.getStaffid(),
                projkey,
                projname,
                startDate,
                endDate
        );
        System.out.println("page = --->" + iPage);
        Map<String, Object> mv = new HashMap<>();
        mv.put("pageBean", iPage);
        return new JsonBean(200, "success", mv);

    }


    /**
     * 参评人 评分树形
     *
     * @param tmplId
     * @return
     */
    @GetMapping(value = "/gzdg/leftTreeByPingfen")
    @ApiOperation("评价评分-左侧评分树形")
    public JsonBean leftTreeByPingfen(
            @ApiParam(name = "tmplId", value = "tmplId", defaultValue = "646171") @RequestParam(value = "tmplId", required = false) BigDecimal tmplId,
            @ApiParam(name = "assId", value = "assId", defaultValue = "734362") @RequestParam(value = "assId", required = false) BigDecimal assId,
            @ApiParam(name = "orgId", value = "orgId", defaultValue = "127634") @RequestParam(value = "orgId", required = false) BigDecimal orgId,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {

        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        TblStaffUtil user = DealUserToken.parseUserToken(token);
        // String tree =
        // this.tblAssesscategoryService.GetTree(tmplId,"/nbkz/pjgl/t08_proj_cat_list1?assId="
        // + assId + "&orgId=" + orgId);
        String tree = this.pjpfService.GetTree(tmplId,
                "/nbkz/pjgl/t08_proj_cat_list1?assId=" + assId + "&orgId=" + orgId, user.getStaffid().toString());
        return new JsonBean(200, "success", tree);
    }


    /**
     * 参评人 评分入口
     *
     * @param
     * @return
     */
    @GetMapping(value = "/pjgl/index")
    @ApiOperation("评价评分-评分入口")
    public JsonBean proj_index(
            @ApiParam(name = "assId", value = "assId", defaultValue = "734362#127634") @RequestParam(value = "assId") String assId,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {

        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }

        Map<String, Object> mv = new HashMap<>();


        String[] val = assId.split("#");
        mv.put("assid", val[0]);
        mv.put("orgId", val[1]);

        return new JsonBean(200, "success", mv);
    }


    /**
     * 评分树形页面跳转
     *
     * @param
     * @return
     */
    @GetMapping(value = "/pjgl/menu_left_tree")
    @ApiOperation("评价评分-评分树形页面跳转")
    public JsonBean proj_menu_left_tree(
            @ApiParam(name = "assId", value = "assId", defaultValue = "734362") @RequestParam(value = "assId", required = false) BigDecimal assId,
            @ApiParam(name = "orgId", value = "orgId", defaultValue = "127634") @RequestParam(value = "orgId", required = false) BigDecimal orgId,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {

        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        TblAssess assess = this.assessService.getById(assId);
        Map<String, Object> mv = new HashMap<>();
        mv.put("tmplId", assess.getAsstemid());
        mv.put("assId", assId);
        mv.put("orgId", orgId);
        return new JsonBean(200, "success", mv);
    }


    /**
     * 需要评分的要数
     *
     * @param
     * @return
     */
    @GetMapping(value = "/pjgl/t08_proj_cat_list1")
    @ApiOperation("评价评分-点击左侧树显示右侧评分要素列表")
    public JsonBean proj_t08_proj_cat_list1(
            @ApiParam(name = "tmplId", value = "tmplId", defaultValue = "646171") @RequestParam(value = "tmplId", required = false) BigDecimal tmplId,
            @ApiParam(name = "nodeId", value = "nodeId", defaultValue = "646901") @RequestParam(value = "nodeId", required = false) BigDecimal nodeId,
            @ApiParam(name = "assId", value = "assId", defaultValue = "734362") @RequestParam(value = "assId", required = false) BigDecimal assId,
            @ApiParam(name = "orgId", value = "orgId", defaultValue = "127634") @RequestParam(value = "orgId", required = false) BigDecimal orgId,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {

        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        Map<String, Object> mv = new HashMap<>();
        TblOrganization organization = this.assessService.queryOrganizationById(orgId);
        if (null != nodeId) {
            TblStaffUtil user = DealUserToken.parseUserToken(token);
            List<ElemGrade> list = this.pjpfService.findElementByassIdAndUserId(nodeId, assId,
                    user.getStaffid(), orgId);
            mv.put("list", list);
            //request.getSession().setAttribute("pjpfysList", list);
        }

        mv.put("organization", organization);
        mv.put("orgId", organization.getOrgid());
        mv.put("assid", assId);
        mv.put("nodeId", nodeId);
        return new JsonBean(200, "success", mv);
    }


    /**
     * 修改要素
     *
     * @param basicId
     * @return
     */
    @GetMapping(value = "/gzdg/def_basic_modify")
    @ApiOperation("评价评分-要素列表-要素详情")
    public JsonBean gzdg_def_basic_modify(
            @ApiParam(name = "basicId", value = "asseleid", defaultValue = "226955") @RequestParam(value = "basicId", required = false) BigDecimal basicId,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {

        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        TblStaffUtil user = DealUserToken.parseUserToken(token);
        TblAssesselement assesselement = this.iTblAssesselementService.getById(basicId);

        Map<String, Object> mv = new HashMap<>();
        QueryWrapper<TblFlow> qw = new QueryWrapper();
        qw.eq("flowbysystem", "1").eq("fatherflowid", 0).eq("company", user.getCurrentOrg().getOrgid());
        List<TblFlow> flows = this.iTblFlowService.list(qw);

        mv.put("conTocat", assesselement.getBusinesstype());
        mv.put("flows", flows);

        mv.put("assesselement", assesselement);

        return new JsonBean(200, "success", mv);
    }


    /**
     * 保存评分
     *
     * @param elements
     * @return
     */

    @PostMapping(value = "/pjgl/t08_proj_cat_list1_save")
    @ApiOperation("评价评分-评价-保存评价")
    public String proj_t08_proj_cat_list1_save(
            @ApiParam(name = "elements", value = "elements", defaultValue = "786684@4@政策与制度 ：1\n" +
                    "流程与系统 1\n" +
                    "控制活动描述：1") @RequestParam(value = "elements", required = false) String elements,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {

        if (!ConstClass.checkToken(token)) {
            return"没有token,或者token错误";
        }
        if (StringUtils.isNotBlank(elements)) {
            String[] elementlist = elements.split("#N#");
            for (int i = 0; i < elementlist.length; i++) {
                if (!elementlist[i].equals("")) {
                    String[] element = elementlist[i].split("@");
                    TblAssessStaff assessStaff = this.iTblAssessStaffService.getById(new BigDecimal(element[0]));
                    // TblAssesselement assesselement =
                    // assessStaff.getTblAssessMark().getTblAssesselement();
                    if (5 >= Double.parseDouble(element[1])) {
                        if (assessStaff.getStatus().equals(2)) {
                            return JsonBean.error("已经提交不能修改");
                        } else {
                            assessStaff.setAssdatetime(LocalDateTime.now());
                            assessStaff.setReason(element[2]);
                            assessStaff.setScore(new BigDecimal(element[1]));
                            assessStaff.setStatus(new BigDecimal(1));
                            // assessStaff.setExamination(element[3]);
                            this.iTblAssessStaffService.updateById(assessStaff);
                            return JsonBean.success();
                        }
                    }
                    return JsonBean.error("评分不能超过标准分！");
                }
            }
            return JsonBean.success();
        }
        return JsonBean.error("保存失败");
    }



    /**
     * 提交评分
     *
     * @param orgId
     * @param assId
     * @param
     * @return
     */
    @PostMapping(value = "/pjgl/sbumitProjCat")
    @ApiOperation("评价评分-评价-全部提交")
    public  String sbumitProjCat(

            @ApiParam(name = "orgId", value = "orgId", defaultValue = "127634") @RequestParam(value = "orgId", required = false) BigDecimal orgId,
            @ApiParam(name = "assId", value = "assId", defaultValue = "786662") @RequestParam(value = "assId", required = false) BigDecimal assId,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {
        if (!ConstClass.checkToken(token)) {
            return"没有token,或者token错误";
        }
        TblStaffUtil user = DealUserToken.parseUserToken(token);
        List<TblAssessStaff> assessStaffs = this.pjpfService.checkSubmit(assId, orgId, user.getStaffid());
        if (assessStaffs.size() > 0) {
            return JsonBean.error("有空缺评分,不能全部提交");
        } else {
            return this.pjpfService.doSubmint(assId, orgId, user.getStaffid());
        }
    }



    /**
     * 评价评分添加附件
     *
     * @param
     * @param request
     * @param asseleid
     * @param
     * @return
     */
    @PostMapping(value = "/pjgl/pjpf_upload")
    @ApiOperation("评价评分-添加附件")
    public  JsonBean pjpf_upload(
            HttpServletRequest request,
            @ApiParam(name = "asseleid", value = "ASSSTAFFID", defaultValue = "") @RequestParam(value = "asseleid", required = false) String asseleid ,
            @ApiParam(name="file",value="附件上传entity",required=true) MultipartFile file,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token
    ) throws Exception {

        if (!ConstClass.checkToken(token)) {
            return ConstClass.tokenFailure();
        }
        TblStaffUtil user = DealUserToken.parseUserToken(token);
        //logger.info("新建---添加评价评分的附件");
        // String assid=request.getParameter("assid");
        // String nodeId=request.getParameter("nodeId");
        // String orgId=request.getParameter("orgId");
        // 代码片段 spingMVC上传文件
       // MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;// request强制转换注意
       // MultipartFile files = mRequest.getFile("file_" + asseleid);

        //TblStaff user = (TblStaff) session.getAttribute("longUser");
        String fileName = file.getOriginalFilename();
        System.out.println("fileName---"+fileName);
        Map<String, Object> mv = new LinkedHashMap<>();
        if (fileName != null && fileName != "") {
            long timeInMillis = Calendar.getInstance().getTimeInMillis();
            String oldname = fileName.substring(0, fileName.lastIndexOf("."));
            String newname = fileName.replace(oldname, "00"+timeInMillis + "sjzgfa");
            System.out.println(file.getInputStream());
            long size = file.getSize();
            try {
                boolean flag = FtpUtil.uploadFile(newname, file.getInputStream());
                if (flag) {
                    log.info("上传成功");
                } else {
                    log.info("上传失败");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            TblAttachment a = new TblAttachment();
            a.setAttname(fileName);
            a.setAttpath(newname);
            a.setAttsize(new BigDecimal(size / 1024));
            a.setUploader(user.getUsername());
            a.setUploadtime(LocalDateTime.now());
            iTblAttachmentService.save(a);
            try {
                if (asseleid != null && asseleid.trim().length() > 0) {
                    TblAssessStaff assessStaff = iTblAssessStaffService.getById(new BigDecimal(asseleid));
                    assessStaff.setAttid(a.getAttid());
                    iTblAssessStaffService.updateById(assessStaff);
                }
            } catch (Exception e) {
                e.printStackTrace();
                // return
                // "redirect:/nbkz/pjgl/t08_proj_cat_list1?nodeId="+nodeId+"&assId="+assid+"&orgId="+orgId;
            }
            mv.put("attid",a.getAttid());
            mv.put("Attachment",a);

        }
        // return
        // "redirect:/nbkz/pjgl/t08_proj_cat_list1?nodeId="+nodeId+"&assId="+assid+"&orgId="+orgId;
        return new JsonBean(200, "上传成功", mv);

    }


    /**
     * 评价评分-删除附件
     *
     * @param
     * @param asseleid
     * @return
     */
    @ApiOperation("评价评分-删除附件")
    @PostMapping(value = "/pjgl/pjpf_fj_del")
    public @ResponseBody String pjpf_fj_del(
            @ApiParam(name = "asseleid", value = "ASSSTAFFID", defaultValue = "") @RequestParam(value = "asseleid", required = false) String asseleid ,
            @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token,
            @ApiParam(name = "attid", value = "attid", defaultValue = "") @RequestParam(value = "attid", required = false)String  attid
    ) throws Exception {

        if (!ConstClass.checkToken(token)) {
            return "token异常";
        }
        log.info("评价评分---删除附件");
        /*
         * String assid=request.getParameter("assid"); String
         * nodeId=request.getParameter("nodeId"); String
         * orgId=request.getParameter("orgId");
         */
        TblAttachment attachment = new TblAttachment();
        if (StringUtils.isNotEmpty(asseleid)) {
//            LambdaUpdateWrapper<TblAssessStaff> wrapper = new LambdaUpdateWrapper<>();
//
//            wrapper.set(TblAssessStaff::getAttid, null);
//
//            wrapper.eq(TblAssessStaff::getAssstaffid, new BigDecimal(asseleid));

            //TblAssessStaff assessStaff =iTblAssessStaffService.getById(new BigDecimal(asseleid));
            //assessStaff.setAttid(null);
            iTblAssessStaffService.updateAttidNullById( new BigDecimal(asseleid));
        }
        if (StringUtils.isNotEmpty(attid)) {
            attachment = iTblAttachmentService.getById(attid);
            iTblAttachmentService.removeById(attid);
            FtpUtil.removeFile(attachment.getAttpath());
            return asseleid;
        }
        // return
        // "redirect:/nbkz/pjgl/t08_proj_cat_list1?nodeId="+nodeId+"&assId="+assid+"&orgId="+orgId;
        return "";
    }


    @GetMapping(value = "/pjgl/pfjg_export")
    @ApiOperation("评价评分-评价-导出excel")
    public  String pfjg_export(
            @ApiParam(name = "orgId", value = "orgId", defaultValue = "") @RequestParam(value = "orgId",required = false) String     orgId,
            @ApiParam(name = "assid", value = "assid", defaultValue = "") @RequestParam(value = "assid")String     assid,
            @ApiParam(name = "nodeId", value = "左侧树节点id", defaultValue = "") @RequestParam(value = "nodeId")String     nodeId,
            @ApiParam(name = "token", value = "登录用户token") @RequestParam(value = "token") String token,
            HttpServletResponse response
    ) throws Exception {
        if (!ConstClass.checkToken(token)) {
            return"没有token,或者token错误";
        }
        TblStaffUtil user = DealUserToken.parseUserToken(token);
        if (StringUtils.isBlank(orgId)) {

            orgId = user.getCurrentOrg().getOrgid().toString();
        }

        log.info("内控合规---评价管理---评价评分---导出Excel");
        response.setContentType("application/binary;charset=UTF-8");
        try {
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String("评价评分".getBytes(), "iso-8859-1") + ".xlsx");
            ServletOutputStream outputStream = response.getOutputStream();
            List<Object[]> objList = this.pjpfService.pjpfExport(new BigDecimal(nodeId),
                    new BigDecimal(assid),user.getStaffid() , new BigDecimal(orgId));
            String[] titles = { "要素编号", "要素名称", "标准分", "审查要点", "评价分", "评价依据", "附件名称" };
            ImportOrExportExcelUtil.exportExcel(titles, objList, outputStream, null);
        } catch (Exception e) {
            log.info("内控合规---评价管理---评价评分---导出Excel失败");
        }
        return null;
    }
}
